package com.woniuxy.rbac.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.rbac.entity.Member;
import com.woniuxy.rbac.service.MemberService;
import com.woniuxy.rbac.service.PermService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class DbRealm extends AuthorizingRealm {
    @Autowired
    private MemberService memberService;

    @Autowired
    private PermService permService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        Member member = (Member) principals.getPrimaryPrincipal();
//        int id = member.getId();
//        List<Perm> perms = permService.getPermsByUserId(id);
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        for (Perm p:perms) {
//            simpleAuthorizationInfo.addStringPermissions(p.getCode());
//        }
//
//
//        return simpleAuthorizationInfo;
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", t.getUsername());
        Member member = memberService.getOne(queryWrapper);
        if (member == null) {
            throw new UnknownAccountException("账号不存在");
        }
        return new SimpleAuthenticationInfo(member, member.getPassword(), getName());
    }
}
